import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import MainLayout from '../layouts/MainLayout.vue'
import ProjectList from '../views/ProjectList.vue'
import TemplateList from '../views/TemplateList.vue'
import SectionList from '../views/SectionList.vue'
import FormList from '../views/FormList.vue'
import ProjectFormManager from '../views/ProjectFormManager.vue'
import FormDesigner from '../components/FormDesigner.vue'
import Login from '../views/Login.vue'
import UserList from '../views/UserList.vue'
import VersionManager from '../views/VersionManager.vue'
import VersionCompare from '../views/VersionCompare.vue'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: { requiresGuest: true }
  },
  {
    path: '/',
    component: MainLayout,
    redirect: '/projects',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/projects',
        name: 'projects',
        component: ProjectList,
        meta: { requiresAuth: true }
      },
      {
        path: '/templates',
        name: 'templates',
        component: TemplateList,
        meta: { requiresAuth: true }
      },
      {
        path: '/sections',
        name: 'sections',
        component: SectionList,
        meta: { requiresAuth: true }
      },
      {
        path: '/forms',
        name: 'forms',
        component: FormList,
        meta: { requiresAuth: true }
      },
      {
        path: '/projects/:projectId/manage',
        name: 'ProjectFormManager',
        component: ProjectFormManager,
        meta: { requiresAuth: true }
      },
      {
        path: '/forms/:formId/config',
        name: 'FormConfig',
        component: FormDesigner,
        meta: { requiresAuth: true, hideMenu: true }
      }
      ,{
        path: '/projects/:projectId/versions',
        name: 'VersionManager',
        component: VersionManager,
        meta: { requiresAuth: true }
      }
      ,{
        path: '/projects/:projectId/versions/compare',
        name: 'VersionCompare',
        component: VersionCompare,
        meta: { requiresAuth: true }
      }
      ,{
        path: '/users',
        name: 'users',
        component: UserList,
        meta: { requiresAuth: true, requiresAdmin: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 a-》b   跳转前守卫   跳转后守卫 
// 组件路由守卫 a-》b   跳转前守卫   跳转后守卫 
// afterEach 跳转后守卫
router.afterEach((to, from) => {
  console.log('跳转后守卫', to, from)
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 只在真正需要时初始化认证状态（避免重复初始化）
  if (!authStore.isAuthenticated && localStorage.getItem('token') && !authStore.isRefreshing) {
    authStore.initAuth()
  }

  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const requiresGuest = to.matched.some(record => record.meta.requiresGuest)
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin)

  if (requiresAuth && !authStore.isLoggedIn) {
    // 需要认证但未登录，跳转到登录页
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if (requiresGuest && authStore.isLoggedIn) {
    // 访客页面但已登录，跳转到首页
    next('/')
  } else if (requiresAdmin && authStore.getUserRole !== 'admin') {
    next('/')
  } else {
    next()
  }
})

export default router 